# 用于生成和修改常见配置文档
import configparser
# 生成软件配置文档
config = configparser.ConfigParser()
config["DEFAULT"] = {'version': '1.0',  # 直接指定
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'

config['topsecret.server.com'] = {}  # 必须先声明为列表{}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'
topsecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
    config.write(configfile)

# 读取配置
conf = configparser.ConfigParser()
conf.read("example.ini")  # 读取
print(conf.defaults())
# 不包含default的section
print(conf.sections())  # ['bitbucket.org', 'topsecret.server.com']
# 获取键对应的值
print(conf['bitbucket.org']['user'])  # hg
conf.get("bitbucket.org", "user")  #hg
# 根据section获取键值列表
items = conf.items('topsecret.server.com')
print(items)
# 根据section获取键列表
options = conf.options("bitbucket.org")
print(options)
# 修改配置
section = conf.add_section("mysql")  # 添加section
# 添加键值
conf.set('mysql', 'version', "5.8")
# 删除section
conf.remove_section('topsecret.server.com')
# 根据键删除
conf.remove_option('bitbucket.org', 'user')
# 保存修改的配置
conf.write(open('example.ini', "w"))

